<template>
    <div>
        <el-card>
            <el-form :inline="true" class="form">
                <el-form-item label="用户名">
                    <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="margin: 10px 0;">
            <el-button type="primary" @click="addUser">添加用户</el-button>
            <el-button type="danger" :disabled="!selectIdArr.length" @click="deleteSelectUser">批量删除</el-button>
            <!--table展示用户信息-->
            <el-table @selection-change="handleSelectionChange" style="margin: 10px 0;" border :data="userArr">
                <el-table-column type="selection" width="80px"></el-table-column>
                <el-table-column type="index" label="#" width="80px"></el-table-column>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="用户名" prop="username"></el-table-column>
                <el-table-column label="用户昵称" prop="name"></el-table-column>
                <el-table-column label="用户角色" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small" icon="User" @click="setRole(scope.row)">分配角色</el-button>
                        <el-button type="primary" size="small" icon="Edit" @click="updateUser(scope.row)">编辑</el-button>
                        <el-popconfirm :title="`确定要删除${scope.row.username}吗？`" width="260px" @confirm="deleteUser(scope.row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页-->
            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :background="true"
                :page-sizes="[5, 10, 20, 30]" :total="total" layout="prev, pager, next, jumper,->,sizes,total"
                @current-change="getHashUser" @size-change="handler" />
        </el-card>
        <!--抽屉结构：完成添加或修改账号信息-->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
            </template>
            <template #default>
                <el-form ref="formRef" :model="userParams" label-width="80px" :rules="rules">
                    <el-form-item label="用户姓名" prop="username">
                        <el-input v-model="userParams.username" placeholder="请输入用户姓名" />
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="name">
                        <el-input v-model="userParams.name" placeholder="请输入用户昵称" />
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                        <el-input v-model="userParams.password" placeholder="请输入用户密码" />
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="save">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <!--抽屉结构：用于分配角色-->
        <el-drawer v-model="drawer1">
            <template #header>
                <h4>分配角色</h4>
            </template>
            <template #default>
                <el-form ref="roleForm" :model="userParams" label-width="80px" :rules="rules">
                    <el-form-item label="用户姓名">
                        <el-input v-model="userParams.username" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="角色列表">
                        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                        <el-checkbox-group v-model="checkedRoleIdList" @change="handleCheckedRoleChange">
                            <el-checkbox v-for="item in allRole" :key="item.id" :label="item.id">
                                {{ item.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer1 = false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { reqAddUser, reqAllRole, reqRemoveUser, reqSelectUser, reqSetUserRole, reqUpdateUser, reqUserInfo } from '@/api/acl/user';
import type { Records, RoleData, SetRoleData, User, UserResponseData } from '@/api/acl/user/type';
import useLayOutSettingStore from '@/store/modules/setting';
import { ElMessage, type CheckboxValueType } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';

let pageNo = ref(1)
let pageSize = ref(5)
let total = ref(0)
let userArr = ref<Records>([])
let drawer = ref(false)
let drawer1 = ref(false)
//收集用户信息的响应式数据
let userParams = reactive({
    id: 0,
    username: '',
    name: '',
    password: ''
})
let formRef = ref()
let selectIdArr = ref<number[]>([])
let keyword = ref('')
//获取模版setting仓库
let seetingStore = useLayOutSettingStore()
//组件挂载完毕
onMounted(() => {
    getHashUser()
})
//获取全部已有的用户信息
const getHashUser = async (pager = 1) => {
    pageNo.value = pager
    let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value);
    if (result.code === 200) {
        total.value = result.data.total
        userArr.value = result.data.records
    }
}
const handler = () => {
    getHashUser()
}
const addUser = () => {
    drawer.value = true
    //清空数据
    Object.assign(userParams, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
    //清除上一次的校验错误提示
    nextTick(() => { //之所以用nextTick，是因为第一次添加用户时，form组件的dom还没渲染出来
        formRef.value.clearValidate()
    })
}

const updateUser = (row: User) => {
    drawer.value = true
    //存储收集已有的用户信息
    Object.assign(userParams, row)
    //清除上一次的校验错误提示
    nextTick(() => { //之所以用nextTick，是因为第一次添加用户时，form组件的dom还没渲染出来
        formRef.value.clearValidate()
    })
}
//保存按钮的回调
const save = async () => {
    //表单校验
    await formRef.value.validate()
    //添加或更新
    if (!userParams.id) {
        reqAddUser(userParams).then(res => {
            if (res.code === 200) {
                ElMessage.success('保存成功')
                drawer.value = false
                getHashUser()
            } else {
                ElMessage.error(res.message)
            }
        })
    } else {
        reqUpdateUser(userParams).then(res => {
            if (res.code === 200) {
                ElMessage.success('更新成功')
                drawer.value = false
                getHashUser(pageNo.value)
                //浏览器自动刷新一次（修改了自己的用户名）
                // window.location.reload()
            } else {
                ElMessage.error(res.message)
            }
        })
    }

}

const cancel = () => {
    drawer.value = false
}
//自定义校验规则
const validatorUserName = (_rule: any, value: any, callback: any) => {
    if (value.length < 3 || value.length > 10) {
        callback(new Error('用户名长度在3-10之间'))
    } else {
        callback()
    }
}
//表单校验规则
const rules = reactive({
    username: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
    { required: true, trigger: 'blur', validator: validatorUserName }
    ],
    name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }]
})

const setRole = (row: User) => {
    //存储收集已有的用户信息
    Object.assign(userParams, row)
    reqAllRole(userParams.id).then(res => {
        if (res.code === 200) {
            allRole.value = res.data.allRolesList
            checkedRoleIdList.value = res.data.assignRoles.map(item => item.id as number)
        } else {
            ElMessage.error(res.message)
            return
        }
    })

    drawer1.value = true

}

let checkAll = ref(false)
let isIndeterminate = ref(false)
let allRole = ref<RoleData[]>([])
let checkedRoleIdList = ref<number[]>([])
const handleCheckAllChange = (val: CheckboxValueType) => {
    checkedRoleIdList.value = val ? allRole.value.map(item => item.id as number) : []
    checkAll.value = val as boolean
    isIndeterminate.value = false
}
const handleCheckedRoleChange = (value: number[]) => {
    let checkedCount = value.length
    checkAll.value = checkedCount === allRole.value.length
    isIndeterminate.value = checkedRoleIdList.value.length > 0 && checkedRoleIdList.value.length < allRole.value.length
}
const confirmClick = () => {
    let params: SetRoleData = {
        userId: userParams.id,
        roleIdList: checkedRoleIdList.value
    }
    reqSetUserRole(params).then(res => {
        if (res.code === 200) {
            ElMessage.success('设置角色成功')
            drawer1.value = false
            getHashUser()
        } else {
            ElMessage.error(res.message)
        }
    })
}
const deleteUser = (id: number) => {
    reqRemoveUser(id).then(res => {
        if (res.code === 200) {
            ElMessage.success('删除成功')
            getHashUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage.error(res.message)
        }
    })
}
//table复选框勾选时触发
const handleSelectionChange = (selection: User[]) => {
    selectIdArr.value = selection.map(item => item.id as number)
}
const deleteSelectUser = () => {
    reqSelectUser(selectIdArr.value).then(res => {
        if (res.code === 200) {
            ElMessage.success('删除成功')
            getHashUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage.error(res.message)
        }
    })
}
const search = () => {
    getHashUser()
}
const reset = () => {
    seetingStore.refresh = !seetingStore.refresh
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>